import React from 'react'
import dayjs from 'dayjs'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'

import useSubs from '../../hooks/useSubs'
import videoStore from '../../store/video'

const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')

const ScreenShot = () => {
  const { curScreenId, playingScreens } = videoStore

  useSubs(({ action, val }) => {
    if (action === 'screenShot') {
      shot(val)
    }
  })

  function shot(action) {
    if (action === 'shot') {
      const { player } = videoStore.findScreenById(curScreenId)
      drawPlayingScreens(player.video)
      download()
    } else if (action === 'shotAll') {
      const zip = new JSZip()
      for (const { player, id } of playingScreens) {
        drawPlayingScreens(player.video)
        zip.file(fileName(), canvas.toDataURL('image/png').substring(22), { base64: true })
      }
      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, 'screeshots.zip')
      })
    }
  }

  function drawPlayingScreens(video) {
    const { videoWidth, videoHeight } = video
    canvas.setAttribute('width', videoWidth)
    canvas.setAttribute('height', videoHeight)
    ctx.drawImage(video, 0, 0, videoWidth, videoHeight)
  }

  function download() {
    const dataUrl = canvas.toDataURL('image/png')
    const link = document.createElement('a')
    link.download = fileName()
    link.href = dataUrl
    link.click()
  }

  function fileName(id = '') {
    return `${id}${dayjs().format('YYYY-MM-DD HH:mm:SSS')}.png`
  }

  return <></>
}

export default ScreenShot
